import React, { Component, Fragment } from 'react';
// import BaseTableComp from "./common/BaseTableComp";
import { WeaLocaleProvider, WeaDialog, WeaFormItem, WeaSearchGroup, WeaTab, WeaCheckbox } from 'ecCom';
import { WeaSwitch, WeaTableNew } from 'comsMobx';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Button } from 'antd';
import { hashHistory } from 'react-router';

const { getLabel } = WeaLocaleProvider;
const { WeaTable } = WeaTableNew;

@inject('superviseStore')
@observer
class SuperviseComponent extends Component {
  constructor(props) {
    super(props);
    const { location } = props;
    const { officalType } = location.query;
    if (officalType && officalType == 1) {
      hashHistory.replace({
        pathname: '/main/offical/customPage',
        query: {
          customListId: -14,
          ...location.query,
        },
      });
      return;
    }
    if (officalType && officalType == 2) {
      hashHistory.replace({
        pathname: '/main/offical/customPage',
        query: {
          customListId: -18,
          ...location.query,
        },
      });
      return;
    }
    if (officalType && officalType == 3) {
      hashHistory.replace({
        pathname: '/main/offical/customPage',
        query: {
          customListId: -22,
          ...location.query,
        },
      });
      return;
    }
    hashHistory.replace({
      pathname: '/main/offical/customPage',
      query: {
        customListId: -10,
        ...location.query,
      },
    });
  }

  componentDidMount() {
    this.getTableDatas = (this.refs.superviseComp && this.refs.superviseComp.wrappedInstance.getTableDatas) || null;
    this.getTabData = (this.refs.superviseComp && this.refs.superviseComp.wrappedInstance.getTabData) || null;
  }

  // componentDidUpdate(prevProps,prevState){
  //   console.log('componentDidUpdate',prevProps.location.query.officalType,this.props.location.query.officalType)
  //   if(prevProps.location.query.officalType !== this.props.location.query.officalType){
  //     this.getTableDatas && this.getTableDatas();
  //     this.getTableDatas && this.getTabData();
  //   }
  // }

  render() {
    return (<span />);
    // const { query } = this.props.location;
    // if (query.officalType) {
    //   let topTitle = getLabel('514401', '发文督办')
    //   if (query.officalType == '2') {
    //     topTitle = getLabel('514402', '收文督办')
    //   }
    //   if (query.officalType == '3') {
    //     topTitle = getLabel('514403', '签报督办')
    //   }
    //   return (
    //     <BaseTableComp
    //       topTitle={topTitle}
    //       tabUrl='/api/odoc/odocSupervise/getSuperviseCount'
    //       searchType={['base', 'advanced']}
    //       searchFormUrl='/api/odoc/odocSupervise/getSuperviseCondition'
    //       tableUrl='/api/odoc/odocSupervise/getSuperviseList'
    //       baseSearchName='requestname'
    //       tabKey='superviseType'
    //       selectedTabKey='0'
    //       onOperatesClick={(record, index) => this.onOperatesClick(record, index)}
    //       getOtherDom={this.getOtherDom}
    //       getColumns={this.getColumns}
    //       ref='superviseComp'
    //       tableParams={toJS(query)}
    //       tabParams={toJS(query)}
    //     />
    //   )
    // } else {
    //   return (
    //     <BaseTableComp
    //       topTitle={getLabel('513073', '公文督办')}
    //       tabUrl='/api/odoc/odocSupervise/getSuperviseCount'
    //       searchType={['base', 'advanced']}
    //       searchFormUrl='/api/odoc/odocSupervise/getSuperviseCondition'
    //       tableUrl='/api/odoc/odocSupervise/getSuperviseList'
    //       baseSearchName='requestname'
    //       tabKey='superviseType'
    //       selectedTabKey='0'
    //       onOperatesClick={(record, index) => this.onOperatesClick(record, index)}
    //       getOtherDom={this.getOtherDom}
    //       getColumns={this.getColumns}
    //       ref='superviseComp'
    //     />
    //   )
    // }
  }

  getColumns = (columns) => {
    let newColumns = columns.map((column) => {
      if (column.dataIndex == 'wbr') {
        return {
          ...column,
          render: (text, record) => (
            <div id={`${record.requestid}todo`}>
              <span style={{ cursor: 'pointer', textDecoration: 'underline' }} onClick={() => this.getTodo(record.requestid, `${record.requestid}todo`)}>{record.wbrspan}</span>
            </div>
          ),
        };
      } else if (column.dataIndex == 'zbr') {
        return {
          ...column,
          render: (text, record) => (
            <div id={`${record.requestid}doing`}>
              <span style={{ cursor: 'pointer', textDecoration: 'underline' }} onClick={() => this.getDoing(record.requestid, `${record.requestid}doing`)}>{record.zbrspan}</span>
            </div>
          ),
        };
      }
      return column;
    });
    return newColumns;
  }

  getOtherDom = () => {
    const { superviseStore } = this.props;
    const { superviseVisible, superviseHide, saveSupervise, superviseForm, urgeForm, urgeHide, urgeVisible, saveUrge, validateForm, superviseconditions,
      delayRequestVisible, delayRequestForm, delayDate, detailDialogVisible, setMobxState, remindSetingVisible, remindSetingForm, validateRemindSetingForm } = superviseStore;
    const getTableDatas = (this.refs.superviseComp && this.refs.superviseComp.wrappedInstance.getTableDatas) || null;
    const getTabData = (this.refs.superviseComp && this.refs.superviseComp.wrappedInstance.getTabData) || null;
    return (
      <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@b4li1w`}>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@60c225`}
          title={getLabel('513073', '公文督办')}
          icon="icon-coms-official"
          iconBgcolor="#f14a2d"
          onCancel={superviseHide}
          visible={superviseVisible}
          style={{ width: 600, height: 400 }}
          hasScroll
          buttons={[
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@sdnj4x@ok`} type="primary" onClick={() => validateForm(superviseForm, saveSupervise, getTableDatas, getTabData)}>{getLabel('33703', '确认')}</Button>,
          ]}
        >
          {this.getSuperviseForm(superviseForm, superviseconditions)}
        </WeaDialog>

        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@qnj9r5`}
          title={getLabel('500432', '催办')}
          icon="icon-coms-official"
          iconBgcolor="#f14a2d"
          onCancel={urgeHide}
          visible={urgeVisible}
          style={{ width: 600, height: 300 }}
          hasScroll
          buttons={[
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lm2y7v@cuiban`} type="primary" onClick={() => validateForm(urgeForm, saveUrge)}>{getLabel('500432', '催办')}</Button>,
          ]}
        >
          {urgeForm.render({ col: 1 })}
        </WeaDialog>

        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@dhe9tg`}
          title={getLabel('513132', '延期处理申请')}
          icon="icon-coms-official"
          iconBgcolor="#f14a2d"
          onCancel={() => setMobxState({ delayRequestVisible: false })}
          visible={delayRequestVisible}
          style={{ width: 600, height: 300 }}
          hasScroll
          buttons={[
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vxfz76@ok`} type="primary" onClick={() => validateForm(delayRequestForm, delayDate, getTableDatas)}>{getLabel('33703', '确认')}</Button>,
          ]}
        >
          {delayRequestForm.render({ col: 1 })}
        </WeaDialog>

        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@hjjaxl`}
          title={getLabel('501321', '督办详情')}
          icon="icon-coms-official"
          iconBgcolor="#f14a2d"
          onCancel={() => setMobxState({ detailDialogVisible: false })}
          visible={detailDialogVisible}
          style={{ width: 800, height: 660 }}
          hasScroll
          buttons={[
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hbbhcb@ok`} type="primary" onClick={() => setMobxState({ detailDialogVisible: false })}>{getLabel('33703', '确认')}</Button>,
          ]}
        >
          {this.getDetailData()}
        </WeaDialog>

        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@bk68gw`}
          title={getLabel('21946', '提醒设置')}
          icon="icon-coms-official"
          iconBgcolor="#f14a2d"
          onCancel={() => setMobxState({ remindSetingVisible: false })}
          visible={remindSetingVisible}
          style={{ width: 800, height: 660 }}
          hasScroll
          buttons={[
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ixdd49@ok`} type="primary" onClick={() => validateRemindSetingForm()}>{getLabel('33703', '确认')}</Button>,
          ]}
        >
          {
            remindSetingForm.render({ col: 1, center: true }, {
              isHide: (key) => {
                const superviseFormParams = superviseForm.getFormParams();
                if (superviseFormParams.superviseRemindType) {
                  if (!superviseFormParams.superviseRemindType.includes('0')) {
                    if (key.includes('before')) {
                      return true;
                    }
                  }
                  if (!superviseFormParams.superviseRemindType.includes('1')) {
                    if (key.includes('after')) {
                      return true;
                    }
                  }
                }
                return false;
              },
            })
          }
        </WeaDialog>
      </Fragment>
    );
  }


  getSuperviseForm(form, conditions) {
    const { superviseStore } = this.props;
    const { checkChange, setMobxState } = superviseStore;
    const { isFormInit } = form;
    let group = [];
    isFormInit && toJS(conditions).map((c, index) => {
      let items = [];
      c.items.map((field) => {
        let col = 1;
        let labelCol = field.labelcol;
        let wrapperCol = field.fieldcol;
        if (field.domkey[0] == 'superviseRemindType') {
          const superviseRemindType = form.getFormParams().superviseRemindType;
          const preValue = superviseRemindType.includes('0') ? '1' : '0';
          const afterValue = superviseRemindType.includes('1') ? '1' : '0';
          items.push({
            com: (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@mrkqpe@${field.domkey[0]}`}
                label={`${field.label}`}
                labelCol={{ span: labelCol }}
                ratio1to2
                error={form.getError(field)}
                tipPosition="bottom"
                wrapperCol={{ span: wrapperCol }}
              >
                <div className="form-item">
                  <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@yf3fzz@${field.domkey[0]}`} value={preValue} onChange={() => checkChange('pre')} content={getLabel('32339', '超时前提醒')} />
                  {superviseRemindType.includes('0') && <i className="icon-coms-Flow-setting" onClick={() => setMobxState({ remindSetingVisible: true })} />}
                </div>
                <div className="form-item">
                  <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@klvgyt@${field.domkey[0]}`} value={afterValue} onChange={() => checkChange('after')} content={getLabel('32175', '超时后提醒')} />
                  {superviseRemindType.includes('1') && <i className="icon-coms-Flow-setting" onClick={() => setMobxState({ remindSetingVisible: true })} />}
                </div>

              </WeaFormItem>
            ),
            col,
          });
        } else {
          items.push({
            com: (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@9nhw95@${field.domkey[0]}`}
                label={`${field.label}`}
                labelCol={{ span: labelCol }}
                ratio1to2
                error={form.getError(field)}
                tipPosition="bottom"
                wrapperCol={{ span: wrapperCol }}
              >
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@xxlxb9@${field.domkey[0]}`} fieldConfig={field} form={form} />
              </WeaFormItem>
            ),
            col,
          });
        }
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@mqnq9c@${index}`} needTigger={false} title={''} showGroup={true} items={items} />);
    });
    return group;
  }

  onOperatesClick(record, index) {
    const { superviseStore } = this.props;
    const { setMobxState, onSupervise, reminder, checkDetails, cancelReminder, getDelayDateCondtion } = superviseStore;
    setMobxState({
      workflowid: record.workflowid,
      operationType: index,
      requestid: record.requestid,
      superviseid: record.superviseid,
    });
    const getTableDatas = (this.refs.superviseComp && this.refs.superviseComp.wrappedInstance.getTableDatas) || null;
    const getTabData = (this.refs.superviseComp && this.refs.superviseComp.wrappedInstance.getTabData) || null;
    // 0 督办 1 催办 2 查看督办详情（督办详情） 3 取消督办 4 查看督办详情（被督办者）5 延期处理申请
    if (index == 0) {
      onSupervise();
    } else if (index == 1) {
      reminder();
    } else if (index == 2) {
      checkDetails();
    } else if (index == 3) {
      cancelReminder(getTableDatas, getTabData);
    } else if (index == 4) {
      checkDetails();
    } else if (index == 5) {
      getDelayDateCondtion();
    }
  }

  getTodo = (requestid, returntdid) => {
    jQuery.ajax({
      url: `/api/odoc/odocNewTodoList/getOperatorPersons?requestid=${requestid}&persontype=0`,
      type: 'post',
      dataType: 'json',
      success(res) {
        try {
          jQuery(`#${returntdid}`).html(res.info);
          jQuery(`#${returntdid}`).parent().attr('title', res.info);
        } catch (e) { }
      },
    });
  }

  getDoing = (requestid, returntdid) => {
    jQuery.ajax({
      url: `/api/odoc/odocNewTodoList/getOperatorPersons?requestid=${requestid}&persontype=1`,
      type: 'post',
      dataType: 'json',
      success(res) {
        try {
          jQuery(`#${returntdid}`).html(res.info);
          jQuery(`#${returntdid}`).parent().attr('title', res.info);
        } catch (e) { }
      },
    });
  }

  getDetailData() {
    const { superviseStore } = this.props;
    const { detailForm, detailTabs, tableStore1, tableStore2, tableStore3, detailSelectKey, setMobxState } = superviseStore;
    return (
      <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@99xflh`}>
        {detailForm.render({ center: true })}
        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@9k338d`}
          datas={toJS(detailTabs)}
          keyParam="viewcondition" // 主键
          selectedKey={detailSelectKey}
          onChange={v => setMobxState({ detailSelectKey: v })}
        />
        {/* 别问我table1 table 2 table3 分别是什么  我也不知道 */}
        {
          detailSelectKey == '0' &&
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@sap4su`}
            comsWeaTableStore={tableStore1}
            bordered
          />
        }

        {
          detailSelectKey == '1' &&
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@vu3d57`}
            comsWeaTableStore={tableStore2}
            bordered
          />
        }

        {
          detailSelectKey == '2' &&
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@sqvcv1`}
            comsWeaTableStore={tableStore3}
            bordered
          />
        }

      </Fragment>

    );
  }
}

export default props => <SuperviseComponent ecId={`${this && this.props && this.props.ecId || ''}_SuperviseComponent@gazh39`} {...props} key={props.location.query.officalType || '0'} />;
